import networkx as ne
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from ctypes import *
import numpy.ctypeslib as npct
import ctypes
from collections import Counter
from networkx import edges
def dufenbu(matrix):  # 测试当前网络度分布
    quantities = np.sum(matrix, axis=1)
    pindu = Counter(quantities)
    pindu = dict(sorted(pindu.items()))
    p_num = list(pindu.values())
    p_k = [x / sum(p_num) for x in p_num]
    x_label = list(pindu.keys())
    return p_k, x_label, quantities
def small_world_NW(N, m, p,t):
    '''
    使用ctypes调用小世界网络c程序
    :param N: 小世界网络个体数
    :param m: m
    :param p: 重连概率
    :return: 返回其接触矩阵
    # '''
    if t == 1:
        FX = ctypes.cdll.LoadLibrary
        lib_ctype = FX("./smallworld.dll")
        reg = np.zeros((N, N), dtype=np.int32)
        lib_ctype.Initial.argtypes = [npct.ndpointer(dtype=np.int, shape=(N, N)), c_int, c_int, c_double]
        lib_ctype.Initial(reg, c_int(N), c_int(m), c_double(p))
    else:
        reg = ne.watts_strogatz_graph(N,m,p)
        reg = np.array(ne.adjacency_matrix(reg).todense())
    pk,x,qaa = dufenbu(reg)
    sns.kdeplot(qaa)
    sns.scatterplot(x,pk)
    plt.show()

def S_word(N,K,p):
    if K%2:
        print("error")
    A=np.zeros((N,N))
    b=int(K/2)
    for i in range(N):
        for j in range(b+1):
            A[i,i-j]=1
            A[i-j,i]=1
    for i in range(b+1):
        for j in range(b+1-i):
            A[N-i-1,0+j]=1
            A[0+j,N-i-1] = 1
    n=np.random.normal(size=[N])
    n= abs(n)/(max(n)-min(n))
    node_list=n<p
    for i in range(N):
        if (node_list[i]):
            for j in range(1,b+1):
                while 1:
                    new_node=np.random.randint(N)
                    if (new_node!=i)and(A[new_node,i]!=1):
                        A[i,new_node]=1
                        break
                if i<N-j:
                    A[i,i+j]=0
                    A[i+j,i]=0
                else:
                    A[i-N+j,i]=0
                    A[i,i-N+j]=0
    return A
ma=small_world_NW(1000,10,0.6,1)
pk,xl,qa = dufenbu(ma)
sns.kdeplot(qa,color = 'red')
sns.scatterplot(xl,pk,color='red')
plt.show()
def juleixi(G,i):
    (m,n)=np.shape(G)
    neighbor_list = []#i的邻居序号
    c=0 #i的邻居对为直连的个数
    for j in range(m):
        if G[i,j]==1:
            neighbor_list.append(j)
    for neighbor1 in neighbor_list:
        for neighbor2 in neighbor_list:
            if G[neighbor1,neighbor2]==1:
                c=c+1
    node_sum = len(neighbor_list)*(len(neighbor_list)-1)
    xishu = c/node_sum#聚类系数
    return xishu


